package cn.zhp.aspect;



import cn.zhp.entity.SysLog;
import cn.zhp.entity.SysUser;
import cn.zhp.service.SysLogService;
import cn.zhp.util.IPUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;


/**
 * aop切面类
 * */
@Component
@Aspect
public class LogAspect {

    @Autowired
    SysLogService logService;

    @Autowired
    HttpServletRequest request;

    /**
     * 切入点配置，记录服务层的日志
     */
    @Pointcut("within(cn.zhp.service..*Impl)")
    public void pointcut(){}


    /**
     * 记录正常日志
     */
    @AfterReturning(pointcut="pointcut()")
    public void after(JoinPoint joinPoint){
//        System.out.println(joinPoint.getTarget().getClass().getSimpleName());

        if(!"SysLogServiceImpl".equals(joinPoint.getTarget().getClass().getSimpleName())) {
            logService.insertSelective(insertLog(null, joinPoint));
        }
    }

    /**
     * 记录异常日志
     * joinPoint(连接点对象)必须放首位
     */
    @AfterThrowing(pointcut = "pointcut()" ,throwing = "e")
    public void afterThrowing(JoinPoint joinPoint,Exception e){
//        System.out.println(e);
        logService.insertSelective(insertLog(e, joinPoint));
    }

    /**
     * 插入日志
     * e:异常对象
     */
    public SysLog insertLog(Exception e, JoinPoint joinPoint){
        SysLog sysLog = new SysLog();

        sysLog.setType(e!=null?"2":"1");//有异常则2
        sysLog.setCreateDate(new Date());
        sysLog.setException(e!=null?e.toString():null);

        if(request!=null){
            SysUser loginUser = (SysUser) request.getSession().getAttribute("loginUser");
            if(loginUser!=null){
                String name = loginUser.getId()+","+ loginUser.getName();
                sysLog.setCreateBy(name);
            }
            sysLog.setRemoteAddr(IPUtils.getClientAddress(request));
            sysLog.setUserAgent(request.getHeader("User-Agent"));
            sysLog.setRequestUri(request.getRequestURI());
            sysLog.setMethod(request.getMethod());

        }

        Object[] args = joinPoint.getArgs();//joinPoint连接点对象获取参数数组

        if (args!=null&&args.length>0){//无方法参数不遍历
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < args.length; i++) {
                sb.append("[参数").append(i+1);
                if(args[i]!=null){
                    sb.append(",类型:").append(args[i].getClass().getSimpleName());
                }
                sb.append(",值:").append(args[i]).append("]");
            }
            sysLog.setParams(sb.toString());
        }
        return sysLog;
    }
}
